package com.dushibao.web;

import com.alibaba.fastjson.JSON;
import com.dushibao.entity.Accessory;
import com.dushibao.service.AccessoryService;
import com.dushibao.service.impl.AccessoryServiceImpl;
import com.dushibao.utils.AppUtils;
import com.dushibao.utils.CommUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    AccessoryService accessoryService = new AccessoryServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        List<Accessory> accessories = new ArrayList<>();

        if(parts!=null){
            for (Part part : parts) {
                String fileName = part.getSubmittedFileName();

                String suffix = fileName.substring(fileName.indexOf("."));

                String newFileName = UUID.randomUUID().toString().replace("-","")+suffix;
                String path = "/upload/"+newFileName;

                String uploadPath = AppUtils.getValue("upload") + path;
                part.write(uploadPath);

                Accessory accessory = new Accessory();
                accessory.setAddTime(LocalDateTime.now());
                accessory.setPath(path);

                accessoryService.save(accessory);

                accessories.add(accessory);
            }
        }

        resp.getWriter().write(JSON.toJSONString(accessories));

    }
}
